import Vue from 'vue';
import Modal from './Modal';
import ModalInstance from './ModalInstance';

const stack=[];
/**
 * 获取一个弹窗实例
 * @param props.icon			类型'info', 'success', 'warning', 'error', 'confirm'
 * @param props.showCancel		是否有取消按钮
 * @param props.title			标题
 * @param props.content			内容
 * @param props.allowHtml		内容是否允许html
 * @param props.max				最大实例数
 * @param props.override		是否覆盖久的实例(必须有max)
 * @return {Promise<unknown>}
 */
function getModalInstance(props){
	//判断是否已经存在相同的提示
	const {icon:icon1,title:title1,content:content1}=props;
	const exist=stack.find(function({instance:{icon,title,content}}){
		return icon1===icon&&title1===title&&content1===content;
	});
	if(exist){
		return exist.promise;
	}
	//判断提示最大数量
	if(props.max&&props.max<=stack.length){
		if(props.override){
			const {instance}=stack.shift();
			if(instance){
				instance.$destroy();
			}
		}else{
			//此处不返回Promise
			return;
		}
	}
	const stackItem={};
	const promise=new Promise(function(resolve,reject){
		const curInstance=new Vue(ModalInstance);
		stackItem.instance=curInstance;
		stack.push(stackItem);
		curInstance.$once('hidden',function(){
			stack.splice(stack.findIndex(function({instance}){
				return curInstance===instance;
			}),1);
			curInstance.$destroy();
		});
		Object.assign(curInstance,props,{
			onConfirm:resolve,
			onClose:reject,
		});
		const element=document.createElement('div');
		document.body.appendChild(element);
		curInstance.$mount(element);
	});
	stackItem.promise=promise;
	return promise;
}
Modal.info=function(props={}){
	props.icon='info';
	props.showCancel=false;
	return getModalInstance(props);
};

Modal.success=function(props={}){
	props.icon='success';
	props.showCancel=false;
	return getModalInstance(props);
};

Modal.warning=function(props={}){
	props.icon='warning';
	props.showCancel=false;
	return getModalInstance(props);
};

Modal.error=function(props={}){
	props.icon='error';
	props.showCancel=false;
	return getModalInstance(props);
};

Modal.confirm=function(props={}){
	props.icon='confirm';
	props.showCancel=true;
	return getModalInstance(props);
};
Modal.getStack=function(){
	return stack;
};
export default Modal;
